package org.example.controller;

import org.example.annotation.LoginCheck;
import org.example.domain.Comment;
import org.example.domain.DiscussPost;
import org.example.domain.User;
import org.example.kafka.Event;
import org.example.kafka.MessageProducer;
import org.example.service.imp.CommentServiceImp;
import org.example.service.imp.DiscussServiceImp;
import org.example.util.CommonParam;
import org.example.util.HutoolUtil;
import org.example.util.UserThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

@Controller
@RequestMapping("/comment/")
public class CommentController {
    @Autowired
    private HutoolUtil hutoolUtil;
    @Autowired
    private CommentServiceImp commentServiceImp;
    @Autowired
    private UserThreadLocalUtil userThreadLocalUtil;
    @Autowired
    private MessageProducer messageProducer;
    @Autowired
    private DiscussServiceImp discussServiceImp;
    /**
     * 这里有一个问题 如果不登录也可以看帖子    那出现评论请求(ajax)  服务端拦截重定向 这里就出现问题 页面不刷新  ajax(局部刷新)不支持重定向(全部刷新) 矛盾
     * 我这里 处理方式为  想看帖子 必须登录
     * @param comment
     * @return
     */
    @LoginCheck
    @ResponseBody
    @PostMapping("save")
    public boolean save(Comment comment){
        if (comment.getEntityType()<0 || hutoolUtil.stringIsEmpty(comment.getContent()) || comment.getTargetId()<0 || comment.getEntityId() <0) return false;
        comment.setStatus(1);
        comment.setCreateTime(new Date());
        User user = userThreadLocalUtil.get();
        comment.setUserId(user.getId());

        int i = commentServiceImp.saveOne(comment);
        Event event = new Event();
        event.setTopic(CommonParam.KAFKA_TOPIC_COMMENT).setUserId(user.getId()).setEntityType(comment.getEntityType());
        //获取entity userid
        if (comment.getEntityType() == 1){
            //这个是帖子评论   获取帖子的用户id
            DiscussPost discussPost = discussServiceImp.searchById(comment.getEntityId());
            event.setEntityUserId(discussPost.getUserId());
            event.setEntityId(comment.getEntityId());
            System.out.println();
        }else if (comment.getEntityType() == 2){
            //这个是评论的评论
            Comment comment1 = commentServiceImp.searchById(comment.getTargetId());
            event.setEntityUserId(comment1.getUserId());
            event.setEntityId(comment.getTargetId());
            System.out.println();
        }
        messageProducer.send(event);
        return true;
    }

}
